import { memo, useEffect, useState } from 'react'
import s from './FileTree.module.less'

function getName(filePath: string) {
  const name = filePath.split(/[\\/]/).pop()
  if (name) {
    return name
  }
  return 'Unkown Name:' + filePath
}

interface FileTreeProps {
  filePath: string
  selectedFile: string
  onClickFile?(filePath: string): void
}

async function checkFile(filePath: string) {
  if (!(await window.api.fileExits(filePath))) {
    alert('no such file or directory: ' + filePath)
    return false
  }
  return true
}

export const FileTree = memo<FileTreeProps>(function FileTreeComponent(
  props: FileTreeProps
): React.ReactElement | null {
  const [subFiles, setSubFiles] = useState<string[]>([])
  const [fileName, setFileName] = useState<string>('')
  const [isDirectory, setIsDirectory] = useState(false)
  const [open, setOpen] = useState(false)

  useEffect(() => {
    window.api.stat(props.filePath).then((s) => {
      if (!s.isDirectory) {
        setFileName(getName(props.filePath))
        setIsDirectory(false)
        setOpen(false)
        setSubFiles([])
      } else {
        window.api.readdir(props.filePath).then((res) => {
          setFileName(getName(props.filePath))
          setIsDirectory(true)
          setOpen(false)
          setSubFiles(res.map((v) => window.api.joinFilePath(props.filePath, v)))
        })
      }
    })
  }, [props.filePath])

  return (
    <div className={s.fileTree}>
      <div
        onClick={
          isDirectory
            ? () => {
                checkFile(props.filePath).then((v) => {
                  if (v) {
                    setOpen(!open)
                  }
                })
              }
            : () => {
                checkFile(props.filePath).then((v) => {
                  if (v) {
                    props.onClickFile?.(props.filePath)
                  }
                })
              }
        }
        className={[
          s.fileTreeItem,
          props.selectedFile === props.filePath ? s.fileTreeItemSelected : ''
        ].join(' ')}
      >
        <div
          className={[
            isDirectory
              ? open
                ? s.fileTreeIconFolderOpen
                : s.fileTreeIconFolder
              : s.fileTreeIconFile,
            s.fileTreeIcon
          ].join(' ')}
        ></div>
        <span>{fileName}</span>
      </div>
      {open && (
        <div className={s.fileTreeSubFiles}>
          {subFiles.map((v, index) => {
            return (
              <FileTree
                filePath={v}
                selectedFile={props.selectedFile}
                key={index}
                onClickFile={props.onClickFile}
              />
            )
          })}
        </div>
      )}
    </div>
  )
})
